﻿namespace AppMain
{
    using System;
    using DotNetty.Transport.Channels;
    using DotNetty.Buffers;
    using System.Collections.Generic;

    /// <summary>
    /// 管理类
    /// </summary>
    public class TestServerHandler : SimpleChannelInboundHandler<object>
    {
        NetRole role = null;

        /// <summary>
        /// 进入的消息
        /// 协议号一定要前后端对应 如果没有对应的handler则不会处理消息
        /// </summary>
        /// <param name="context"></param>
        /// <param name="message"></param>
        protected override void ChannelRead0(IChannelHandlerContext context, object message)
        {
            PBMessage pbs = message as PBMessage;
            ProtocolEventMgr.Instance.dispatch(role, pbs);
        }

        //public override void ChannelReadComplete(IChannelHandlerContext context) => context.Flush();

        /// <summary>
        /// 初始化调用
        /// </summary>
        /// <param name="ctx"></param>
        public override void ChannelActive(IChannelHandlerContext ctx)
        {
            Console.WriteLine("<<<<----客户端链接 ");
            role = new NetRole(new RoleAttrMap());
            role.setContext(ctx);
        }

        public override void HandlerRemoved(IChannelHandlerContext context)
        {
            Console.WriteLine("客户端断开连接--->>>> ");
            //写入sql
            //"update tb_role_info set nickname='zhang',level='888' where roleid='1003' "
            //如果玩家当前在副本中
            string updateSql = "";
            DynamicBox3D box3d = role.box3D;
            long scenecopyuid = role.AttrMap.getAttr<long>(RoleAttr.CopySceneUID).Value;
            long scenecopyid = role.AttrMap.getAttr<long>(RoleAttr.CopySceneId).Value;

            if (scenecopyuid > 0)
            {
                updateSql = string.Format("update tb_role_info set copySceneId='{0}',copySceneUID='{1}',cx='{2}',cy='{3}',cz='{4}' where roleId='{5}'", scenecopyid, scenecopyuid, box3d.posX, box3d.posY, box3d.posZ, role.UID);
            }
            else
            {
                long sceneid = role.AttrMap.getAttr<long>(RoleAttr.SceneId).Value;
                updateSql = string.Format("update tb_role_info set sceneId='{0}',posx='{1}',posy='{2}',posz='{3}' where roleId='{4}'", sceneid, box3d.posX, box3d.posY, box3d.posZ, role.UID);
            }
            SqlMgr.Instance.update(updateSql);
            RoleMgr.Instance.removeRole(role);
        }

        //public override void ExceptionCaught(IChannelHandlerContext ctx, Exception e)
        //{
        //    Console.WriteLine("{0}{1}", "客户端断开连接-->", e.ToString());

        //    ChannelGroup.Instance.remove(ctx.Channel);
        //    ctx.CloseAsync();
        //}
    }
}
